import pymysql



def main():
	db = connect()
	if db is None:
		print("连接数据库失败")
		return
	cursor = db.cursor()
	try:
		for i in range(len(data)):
			sql = "INSERT INTO person (username, age, sex, high) VALUES (%s, %s, %s, %s)"
			cursor.execute(sql, (data[i]["username"], data[i]["age"], data[i]["sex"], data[i]["high"]))
	except pymysql.MySQLError as e:
		print("插入失败:", e)
		db.rollback()
	else:
		print("插入成功")
		db.commit()

	cursor.close()
	db.close()

def connect():
	try: 
		conn = pymysql.connect(
			host='localhost',
			user='root',
			password='123456',
			database='try_db'
		)
	except pymysql.MySQLError as e:
		print("连接数据库失败:", e)
		return None
	return conn

# 10个
data = [
	{"username": "test_user1", "age": 25, "sex":"男", "high": 175},
	{"username": "test_user2", "age": 21, "sex":"男", "high": 165},
	{"username": "test_user3", "age": 26, "sex":"女", "high": 155},
	{"username": "test_user4", "age": 23, "sex":"男", "high": 166},
	{"username": "test_user5", "age": 30, "sex":"女", "high": 172},
	{"username": "test_user6", "age": 32, "sex":"男", "high": 181},
	{"username": "test_user7", "age": 34, "sex":"女", "high": 178},
	{"username": "test_user8", "age": 40, "sex":"女", "high": 166},
	{"username": "test_user9", "age": 36, "sex":"男", "high": 176},
	{"username": "test_user10", "age": 19, "sex":"男", "high": 163}
]

main()